package czk.concrent.juc.countDOwnLatch.practice;

import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 一个资源等待多个资源
 *
 * @Author:ChenZhangKun
 * @Date: 2021/10/23 15:40
 */
public class OneSourceWaitMostSource {
    public static void main(String[] args) {
        callApi();
    }

    public static void callApi() {
        CountDownLatch latch = new CountDownLatch(3);
        System.out.println("进入api");
        System.out.println("调用服务A了");
        FutureTask<Integer> futureTask1 = new FutureTask<>(new BaseService(latch));
        new Thread(futureTask1, "底层服务A").start();
        //调用服务B
        System.out.println("调用B服务");
        FutureTask<Integer> ft2 = new FutureTask<>(new BaseService(latch));
        new Thread(ft2, "底层服务B").start();
        //调用服务C
        System.out.println("调用C服务");
        FutureTask<Integer> ft3 = new FutureTask<>(new BaseService(latch));
        new Thread(ft3, "底层服务C").start();
        try {
            System.out.println("等待子服务调用结果。。。");
            latch.await();
            System.out.println("API结果为：【" + (futureTask1.get() + ft2.get() + ft3.get()) + "】");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }
}

class BaseService implements Callable<Integer> {
    private CountDownLatch latch;

    public BaseService(CountDownLatch latch1) {
        latch = latch1;
    }

    @Override
    public Integer call() throws Exception {
        Thread.sleep((int) Math.random() * 1000);
        Integer re = (int) (Math.random() * 10000);
        latch.countDown();
        System.out.println(Thread.currentThread().getName() + "服务执行完毕，返回【" + re + "】");
        return re;
    }

}
